#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    ,totalDuration(0)
{
    ui->setupUi(this);
    srand((size_t)time(nullptr));//利用时间戳当随机种子
    initUI();
    initPlayer();//初始化音乐播放器
}

Widget::~Widget()
{
    delete ui;
}

void Widget::initUI()
{
    this->setWindowFlag(Qt::WindowType::FramelessWindowHint);
    this->setAttribute(Qt::WA_TranslucentBackground);//设置窗口背景透明
    //给窗口设置阴影效果
    QGraphicsDropShadowEffect* shadowEffect = new QGraphicsDropShadowEffect(this);
    shadowEffect->setOffset(0,0);
    shadowEffect->setColor("#000000");
    shadowEffect->setBlurRadius(10);
    this->setGraphicsEffect(shadowEffect);
    //设置左侧窗口按钮
    ui->Rec->setIcon(":/images/rec.png","推荐",0);
    ui->Music->setIcon(":/images/music.png","音乐馆",1);
    ui->audio->setIcon(":/images/radio.png","电台",2);
    ui->like->setIcon(":/images/like.png","我喜欢",3);
    ui->local->setIcon(":/images/local.png","本地音乐",4);
    ui->recent->setIcon(":/images/recent.png","最近播放",5);

    //设置一个缺省页面，让推荐页面在运行后就以被点中出现
    defaultRec();
    //启动动画效果
    //ui->like->showAnimation();
    RandomPicture();
    //为推荐页面添加图片
    ui->recMusicBox->initRecBoxUi(RandomPicture(),1);
    ui->supplyMusicBox->initRecBoxUi(RandomPicture(),2);
    //设置后我喜欢，本地音乐，最近播放的页面
    ui->likePage->setMusicListType(PageType::LIKE_PAGE);
    ui->likePage->setCommonPageUi("我喜欢",":/images/ilikebg.png");
    ui->localPage->setMusicListType(PageType::LOCAL_PAGE);
    ui->localPage->setCommonPageUi("本地音乐",":/images/localbg.png");
    ui->recentPage->setMusicListType(PageType::HISTORY_PAGE);
    ui->recentPage->setCommonPageUi("最近播放",":/images/recentbg.png");

    ui->Play->setIcon(QIcon(":/images/play3.png"));
    ui->playMode->setIcon(QIcon(":/images/list_play.png"));

    volumeTool = new VolumeTool(this);

    //绑定左侧按钮的槽函数
    conncetSignalAndSlot();

}

void Widget::conncetSignalAndSlot()
{
    connect(ui->Rec,&btForm::clicked,this,&Widget::onBtFromClicked);
    connect(ui->Music,&btForm::clicked,this,&Widget::onBtFromClicked);
    connect(ui->audio,&btForm::clicked,this,&Widget::onBtFromClicked);
    connect(ui->like,&btForm::clicked,this,&Widget::onBtFromClicked);
    connect(ui->local,&btForm::clicked,this,&Widget::onBtFromClicked);
    connect(ui->recent,&btForm::clicked,this,&Widget::onBtFromClicked);

    connect(ui->likePage,&CommonPage::updateLikeMusic,this,&Widget::onUpdateLikeMusic);
    connect(ui->localPage,&CommonPage::updateLikeMusic,this,&Widget::onUpdateLikeMusic);
    connect(ui->recentPage,&CommonPage::updateLikeMusic,this,&Widget::onUpdateLikeMusic);

    //处理播放全部按钮
    connect(ui->likePage,&CommonPage::playAll,this,&Widget::onPlayAll);
    connect(ui->localPage,&CommonPage::playAll,this,&Widget::onPlayAll);
    connect(ui->recentPage,&CommonPage::playAll,this,&Widget::onPlayAll);

    connect(ui->Play,&QPushButton::clicked,this,&Widget::onPlayMusic);
    connect(ui->playUp,&QPushButton::clicked,this,&Widget::onPlayUpClicked);
    connect(ui->playDown,&QPushButton::clicked,this,&Widget::onPlayDownClicked);

    connect(ui->playMode,&QPushButton::clicked,this,&Widget::onPlaybackModeClicked);

    connect(ui->likePage,&CommonPage::playMusicByIndex,this,&Widget::playMusicByIndex);
    connect(ui->localPage,&CommonPage::playMusicByIndex,this,&Widget::playMusicByIndex);
    connect(ui->recentPage,&CommonPage::playMusicByIndex,this,&Widget::playMusicByIndex);

    connect(volumeTool,&VolumeTool::setSilence,this,&Widget::setMusicSilence);

    connect(ui->processBar,&MusicSlider::setMusicSilderPosition,this,&Widget::onMusicSliderChanged);



}

void Widget::initPlayer()
{
    //创建音乐播放器
    player = new QMediaPlayer(this);
    //创建播放列表
    playList = new QMediaPlaylist(this);

    //设置播放模式，默认为顺序播放
    playList->setPlaybackMode(QMediaPlaylist::Loop);

    //将播放列表设置给播放器
    player->setPlaylist(playList);
    //设置默认音量为20
    player->setVolume(20);
    connect(player,&QMediaPlayer::stateChanged,this,&Widget::onPlayStateChanged);
    connect(playList,&QMediaPlaylist::playbackModeChanged,this,&Widget::onPlaybackModeChanged);
    //播放列表发射改变，奖播放音乐收藏到历史记录
    connect(playList,&QMediaPlaylist::currentIndexChanged,this,&Widget::onCurrentIndexChanged);

    connect(volumeTool,&VolumeTool::setMusicVolume,this,&Widget::setMusicVolume);

    connect(player,&QMediaPlayer::durationChanged,this,&Widget::onDurationChanged);

    connect(player,&QMediaPlayer::positionChanged,this,&Widget::onPositionChanged);

    connect(player,&QMediaPlayer::metaDataAvailableChanged,this,&Widget::onMetaDataAvailableChanged);
}

void Widget::playAllMusicOfCommonPage(CommonPage *page, int index)
{
    currentPage = page;
    updateBtformAnima();
    //清空之前playlist的歌曲
    playList->clear();
    //添加当前要播放的page页面的所有歌曲
    page->addMusicToPlaylist(musiclist,playList);
    playList->setCurrentIndex(index);
    player->play();
}

void Widget::updateBtformAnima()
{
    qDebug()<<"更新动画效果";
    //获取currentPage在stackedWidget中的索引
    int index = ui->stackedWidget->indexOf(currentPage);

    if(-1 == index)
    {
        qDebug()<<"该页面不存在";
        return;
    }
    //获取Widget界面上所有的btform
    QList<btForm*> btforms = this->findChildren<btForm*>();
    for(auto* btform:btforms)
    {
        if(btform->getPageId() == index)
        {
            btform->showAnimation(true);
        }
        else
        {
            btform->showAnimation(false);
        }
    }
}

void Widget::onBtFromClicked(int id)
{
    //利用findChildren函数获取当前页面所有btFrom按钮类型对象
    QList<btForm*> buttonList = this->findChildren<btForm*>();
    //遍历对象，把除当前id的效果都清除
    for(auto* bt:buttonList)
    {
        if(bt->getPageId() != id)
        {
            //清除效果
            bt->clearBg();
        }
    }
    ui->stackedWidget->setCurrentIndex(id);
}

void Widget::onUpdateLikeMusic(bool isLike, QString musicId)
{
    auto it = musiclist.findMusicByMusicId(musicId);
    if(it!=musiclist.end())
    {
        it->setIsLike(isLike);
    }

    ui->likePage->reFresh(musiclist);
    ui->localPage->reFresh(musiclist);
    ui->recentPage->reFresh(musiclist);
}




void Widget::on_quit_clicked()
{
    this->close();
}

QJsonArray Widget::RandomPicture()
{
    QVector<QString> vecImageName;
    QDir dir(":/images/rec");
    QStringList files = dir.entryList(QDir::Files|QDir::NoDotAndDotDot);
    //输出文件名
    qDebug()<<"目录下的文件"<<endl;
    for(const QString& file:files)
        vecImageName.push_back(file);
    for(auto&x:vecImageName)
        qDebug()<<x<<endl;
    //因为每日推荐肯定都是随机的，所以我们需要把数组内容的元素给打散，利用随机函数random_shuffle,记得添加随机种子
    std::random_shuffle(vecImageName.begin(),vecImageName.end());
    //打散后，将其用Json序列化
    QJsonArray objArray;//存储Json对象
    for(int i = 0;i<vecImageName.size();++i)
    {
        QJsonObject obj;
        obj.insert("path",":/images/rec/"+vecImageName[i]);
        QString strText = QString("推荐-%1").arg(i,3,10,QChar('0'));
        obj.insert("text",strText);
        objArray.append(obj);
    }

    return objArray;
}

void Widget::mousePressEvent(QMouseEvent *event)
{
    //检测鼠标左键按下
    if(event->button() == Qt::LeftButton)
    {
        //获取窗口与鼠标的相对位置
        dragPosition = event->globalPos()-frameGeometry().topLeft();
        //qDebug()<<1<<endl;
        return;
    }
    //其他事件交给父类处理
    QWidget::mousePressEvent(event);

}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    //通过相对位置改变窗口位置
    if(event->buttons() == Qt::LeftButton)//event->buttons() 持续获取
    {
        move(event->globalPos()-dragPosition);
        return;
    }

    //其他事件交给父类处理
    QWidget::mouseMoveEvent(event);
}

void Widget::defaultRec()
{
    //ui->Rec->changeColor();
    ui->stackedWidget->setCurrentIndex(4);
    currentPage = ui->localPage;
}


void Widget::on_volume_clicked()
{
    //1.先获取到volume图标的下标位置 全局
    QPoint point = ui->volume->mapToGlobal(QPoint(ui->volume->width()/2,ui->volume->height()/2));

    //2，计算volume窗口的左上角位置
    QPoint volumeLeftTop = point - QPoint(volumeTool->width()/2,volumeTool->height());
    //3.移动窗口
    volumeTool->move(volumeLeftTop);
    volumeTool->show();
}

void Widget::on_addLocal_clicked()
{
    //添加音乐的槽函数
    QFileDialog fileDialog(this);//绑定当前窗口
    //设置当前窗口标题
    fileDialog.setWindowTitle("添加本地下载音乐");

    //设置文件对话框默认的打开路径
    QDir dir(QDir::currentPath()); //设置当前路径
    dir.cdUp();//返回上级路径
    QString projectPath = dir.path();//获取路径
    projectPath+="/Music/musics";

    fileDialog.setDirectory(projectPath);//打开窗口的路径

    //一次性选中多个
    fileDialog.setFileMode(QFileDialog::ExistingFiles);

    //利用MIME来过滤，不过此处没有限制，真正的限制在MusicList内部
    QStringList mimeTypeFilters;
    mimeTypeFilters<<"application/octet-stream";
    fileDialog.setMimeTypeFilters(mimeTypeFilters);

    if(QDialog::Accepted == fileDialog.exec())
    {
        //获取选中的文件
        QList<QUrl> fileUrls = fileDialog.selectedUrls();
        musiclist.addMusicByUrl(fileUrls);
        //onBtFromClicked(4);
        ui->stackedWidget->setCurrentIndex(4);//因为添加到本地音乐
        ui->localPage->reFresh(musiclist);//刷新本地音乐列表

        //将localpage中的歌曲添加到媒体播放列表中
        ui->localPage->addMusicToPlaylist(musiclist,playList);
    }

}

void Widget::onPlayAll(PageType pageType)
{
    qDebug()<<"播放全部";
    //通过pagetypea找到对应的commonPage页面
    CommonPage* page;
    page = ui->localPage;
    switch (pageType) {
        case LOCAL_PAGE:
            page = ui->localPage;
        break;
        case LIKE_PAGE:
            page = ui->likePage;
        break;
        case HISTORY_PAGE:
            page = ui->recentPage;
        break;
    default:
        qDebug()<<"不支持~";
    }
    playAllMusicOfCommonPage(page,0);

}

void Widget::onPlayMusic()
{
    qDebug()<<"播放音乐";
    //如果处于播放状态就暂停，如果处于暂停暂停就播放，如果处于默认停止状态就播放
    if(QMediaPlayer::PlayingState == player->state())
    {
        player->pause();
        qDebug()<<"pause";
    }
    else if(QMediaPlayer::PausedState == player->state())
    {
        player->play();
        qDebug()<<"play";
    }
    else if(QMediaPlayer::StoppedState == player->state())
    {
        player->play();
        qDebug()<<"play";
    }
    else
    {
        qDebug()<<player->errorString();
    }

}

void Widget::onPlayStateChanged()
{
    qDebug()<<"播放状态改变";
    if(player->state() == QMediaPlayer::PlayingState)
    {
        ui->Play->setIcon(QIcon(":/images/play_on.png"));
    }
    else
    {
        ui->Play->setIcon(QIcon(":/images/play3.png"));
    }
}

void Widget::onPlayUpClicked()
{
    playList->previous();
}

void Widget::onPlayDownClicked()
{
    playList->next();
}

void Widget::onPlaybackModeClicked()
{
    qDebug()<<"改变模式";
    //顺序->循环->单曲->循环
    if(QMediaPlaylist::Loop == playList->playbackMode())
    {
        ui->playMode->setToolTip("随机播放");
        playList->setPlaybackMode(QMediaPlaylist::Random);
    }
    else if(QMediaPlaylist::Random == playList->playbackMode())
    {
        ui->playMode->setToolTip("单曲循环");
        playList->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
    }
    else if(QMediaPlaylist::CurrentItemInLoop == playList->playbackMode())
    {
        ui->playMode->setToolTip("顺序播放");
        playList->setPlaybackMode(QMediaPlaylist::Loop);
    }
    else
    {
        qDebug()<<"不支持~";
    }
}

void Widget::onPlaybackModeChanged(QMediaPlaylist::PlaybackMode playbackMode)
{
    if(QMediaPlaylist::Loop == playbackMode)
    {
        ui->playMode->setIcon(QIcon(":/images/list_play.png"));
    }
    else if(QMediaPlaylist::Random == playbackMode)
    {
        ui->playMode->setIcon(QIcon(":/images/shuffle_2.png"));
    }
    else if(QMediaPlaylist::CurrentItemInLoop == playbackMode)
    {
        ui->playMode->setIcon(QIcon(":/images/single_play.png"));
    }
    else
    {
        qDebug()<<"不支持~";
    }

}

void Widget::playMusicByIndex(CommonPage *page, int index)
{
    qDebug()<<"准备播放音乐";
    playAllMusicOfCommonPage(page,index);
}

void Widget::onCurrentIndexChanged(int index)
{
    currentIndex = index;
    const QString& musicId = currentPage->getMusicIdByIndex(index);
    auto it = musiclist.findMusicByMusicId(musicId);
    if(it != musiclist.end())
    {
        it->setIsHistory(true);
    }
    ui->recentPage->reFresh(musiclist);
}

void Widget::setMusicSilence(bool isMuted)
{
    player->setMuted(isMuted);
}

void Widget::setMusicVolume(int volume)
{
    player->setVolume(volume);
}

void Widget::onDurationChanged(qint64 duration)
{
    ui->totleTime->setText(QString("%1:%2").arg(duration/1000/60,2,10,QChar('0')).arg(duration/1000%60,2,10,QChar('0')));
    totalDuration = duration;
}

void Widget::onPositionChanged(qint64 duration)
{
    ui->currentTime->setText(QString("%1:%2").arg(duration/1000/60,2,10,QChar('0')).arg(duration/1000%60,2,10,QChar('0')));
    ui->processBar->setStep(duration/(float)totalDuration);
}

void Widget::onMusicSliderChanged(float value)
{
    qint64 duration = (qint64)(totalDuration*value);

    ui->currentTime->setText(QString("%1:%2").arg(duration/1000/60,2,10,QChar('0')).arg(duration/1000%60,2,10,QChar('0')));

    player->setPosition(duration);
}

void Widget::onMetaDataAvailableChanged(bool available)
{
   if(available)
   {
       QString musicId = currentPage->getMusicIdByIndex(currentIndex);
       auto it = musiclist.findMusicByMusicId(musicId);
       QString musicName = "未知歌曲";
       QString musicSinger = "未知歌手";
       if(it != musiclist.end())
       {
           musicName = it->getMusicName();
           musicSinger = it->getMusicSinger();
       }
       //将数据设置到下方
       ui->musicName->setText(musicName);
       ui->musicSinger->setText(musicSinger);

       //获取音乐封面
       QVariant coverimage = player->metaData("ThumbnailImage");
       if(coverimage.isValid())
       {
           QImage image = coverimage.value<QImage>();
           ui->musicCover->setPixmap(QPixmap::fromImage(image));
           currentPage->setMusicImage(QPixmap::fromImage(image));
       }
       else
       {
           qDebug()<<"歌曲没有封面图";
           QString path = ":/images/rec/001.png";
           ui->musicCover->setPixmap(path);
           currentPage->setMusicImage(path);
       }
       ui->musicCover->setScaledContents(true);
   }
   else
   {
       qDebug()<<"数据不可用";
       ui->musicName->setText("未知歌曲");
       ui->musicSinger->setText("未知歌手");
   }
}
